import random
import time

import numpy as np
import pandas as pd


'''计算单词在tag类中出现的次数'''
def countWord(word,tag):
    count = 0
    for sentence in tag:
        for w in sentence.split():
            if(word == w):
                count = count + 1
    print(word,":  ",count)
    return count

'''计算文本str属于tag类的朴素贝叶斯概率'''
def caculateNBP(str,tag,Ptag,All,tagNum):
    str = str.lower()
    words = str.split(" ")
    pList = []
    for word in words:
        P = (1+countWord(word,tag))/(All + tagNum)
        pList.append(P)
    NBP = 1
    print(pList)
    for P in pList:
        NBP = NBP * P
    NBP = NBP*Ptag
    return NBP
'''训练数据'''
texts = ["A great game", "The election was over", "Very clean match", "A clean but forgettable game", "It was a close election"]

Sports = ["A great game", "Very clean match", "A clean but forgettable game"]

NotSports = ["The election was over", "It was a close election"]
'''转小写'''
texts2 = [s.lower() for s in texts if isinstance(s,str)==True]
Sports2 = [s.lower() for s in Sports if isinstance(s,str)==True]
NotSports2 = [s.lower() for s in NotSports if isinstance(s,str)==True]
'''计算P(Sports)和P(NOT SPORTS)'''
Psports = len(Sports)/len(texts)
PnotSports = len(NotSports)/len(texts)
str = "100"
allWords = []#所有可能的单词
for sentence in texts2:
    temp = sentence.split(" ")
    allWords = allWords + temp
allWords = set(allWords)
allWords = list(allWords)
lenAllWords = len(allWords)#所有可能的单词数量

numofSports = 0#Sports类文本的单词数
for sentence in Sports2:
    temp = len(sentence.split())
    numofSports = numofSports + temp

numofNotSports = 0#notSports类文本的单词数
for sentence in NotSports2:
    temp = len(sentence.split())
    numofNotSports = numofNotSports + temp

str = "A very close game"
print("计算sports概率：---------------------------------------------")
pSports = caculateNBP(str,Sports2,Psports,numofSports,lenAllWords)
print("P(STR|SPORTS)= ",pSports)
print("计算not sports概率：---------------------------------------------")
pNotSports = caculateNBP(str,NotSports2,PnotSports,numofNotSports,lenAllWords)
print("P(STR|NOTSPORTS)= ", pNotSports)
print("分类结果：   ")
if(pSports > pNotSports):
    print("文本  ",str,"  可以被分为Sports类")
else:
    print("文本  ",str,"  可以被分为Not Sports类")


